package org.csu.mypetstore_seller.controller;


import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.csu.mypetstore_seller.domain.Category;
import org.csu.mypetstore_seller.domain.Product;
import org.csu.mypetstore_seller.service.CategoryService;
import org.csu.mypetstore_seller.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

@Controller
@Slf4j
@RequestMapping("/category2")
public class Category2Controller {
    @Autowired
    HttpSession httpSession;

    @Autowired
    private ProductService productService;

    @GetMapping("/view")
    public String categoryView(Model model, @RequestParam("catid") String id){
        log.info("查看分类详情，分类ID：{}", id);
        model.addAttribute("productList",productService.getProductList(id));
        httpSession.setAttribute("categoryId",id);
        return "catalog/category2";
    }
   //点击新增按钮
    @GetMapping("/addproduct")
    public String addproduct(Model model,@RequestParam("catid")String id){
        log.info("打开新增商品页面");
        model.addAttribute("productList",productService.getProductList(id));
        httpSession.setAttribute("categoryId",id);
        return "catalog/addcategory";
    }
    //点击编辑按钮时触发
    @GetMapping("/editeView")
    public String editeView(@RequestParam("productId") String productId, Model model){
        log.info("访问商品编辑页面，商品ID：{}", productId);
        //获得要编辑的产品详情
        model.addAttribute("product", productService.getProductByproductId(productId));
        return "catalog/editeProduct";
    }

    //编辑页面点击保存时触发
    @PostMapping("/edite")
    public void edite(
            @RequestParam("productId") String productId,
            @RequestParam("categoryId") String categoryId,
            @RequestParam("name") String name,
            @SessionAttribute(value = "categoryId") String id,
            HttpServletResponse response
    ) throws IOException {
        log.info("修改商品信息，商品ID：{}，商品名称：{}，分类ID：{}", productId, name, categoryId);
        Product product=new Product();
        product.setCategoryId(categoryId);
        product.setName(name);
        product.setProductId(productId);
        productService.updateProduct(product,productId);
        log.info("商品信息修改成功");
        response.sendRedirect("/category2/view?catid="+id);
    }

    @GetMapping("/delete")
    public void delete(@SessionAttribute("categoryId") String id,@RequestParam("name") String name, HttpServletResponse response) throws IOException {
        log.info("删除商品，分类ID：{}，商品名称：{}", id, name);
        productService.deleteProductByName(name);
        response.sendRedirect("/category2/view?catid="+id);
    }
    @PostMapping("/add")
    public void addCategory(
            @RequestParam("productId") String productId,
            @RequestParam("name") String name,
            @RequestParam("categoryId") String categoryId,
            @RequestParam("description") String description,
            @SessionAttribute("categoryId") String id,
            //HttpSession session,
            @RequestParam("image") MultipartFile image, // 接收上传的文件
            HttpServletResponse response) throws IOException {

//        String id = (String) session.getAttribute("categoryId");
//        if (id == null) {
//            throw new IllegalArgumentException("分类ID不能为空");
//        }
        // 校验用户输入是否为空
        if (productId == null || productId.trim().isEmpty()) {
            throw new IllegalArgumentException("序列号不能为空");
        }
        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException("名字不能为空");
        }
        if (description == null || description.trim().isEmpty()) {
            throw new IllegalArgumentException("简介不能为空");
        }
        if (image == null || image.isEmpty()) {
            throw new IllegalArgumentException("请上传图片");
        }

        // 校验文件类型
        String originalFilename = image.getOriginalFilename();
        System.out.println(originalFilename);
        if (originalFilename == null || !originalFilename.matches(".*\\.(jpg|jpeg|png|gif)$")) {
            throw new IllegalArgumentException("只支持上传 jpg, jpeg, png, gif 格式的图片");
        }
//        // 检查 productId 是否已存在
//        Product existingProduct = productService.getProductByproductId(productId);
//        if (existingProduct != null) {
//            throw new IllegalArgumentException("商品ID已存在，请使用其他ID");
//        }

        log.info("添加新商品，商品ID：{}，商品名称：{}，分类ID：{}", productId, name, categoryId);

        // 保存上传的图片到 images 文件夹

        // 获取文件后缀（包括点，例如 ".jpg"）
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 定义外部目录路径
        String externalImagePath = "C:/mypetstore/image/"; // Windows
        // 确保目录存在
        File imageDir = new File(externalImagePath);
        if (!imageDir.exists()) {
            imageDir.mkdirs(); // 创建目录
        }
        // 动态生成图片文件名
        String imageName = name + fileExtension;
        //String imageName = name + ".gif"; // 图片文件名
        //String imagePath = "mypetstore-seller/src/main/resources/static/images/" + imageName; // 图片保存路径
        String imagePath = externalImagePath + imageName;
        // 将文件保存到指定路径
        FileUtils.writeByteArrayToFile(new File(imagePath), image.getBytes());

        // 设置 categoryId
        categoryId = id;

        // 创建并保存商品信息
        Product product = new Product();
        product.setProductId(productId);
        product.setCategoryId(categoryId);
        product.setName(name);
        //product.setDescription("<image src=\"images/" + name + fileExtension+"\">" + description);
        product.setDescription("<img src=\"/image/" + imageName + "\"+ width=\"125\" height=\"125\">" + description);
        product.setDeleteFlag(0); // 标记为有效
        productService.insertProduct(product);

        log.info("商品添加成功");
        response.sendRedirect("/category2/view?catid=" + categoryId);
    }

//    @PostMapping("/add")
//    public void addCategory(
//            @RequestParam("productId") String productId,
//            @RequestParam("name") String name,
//            @RequestParam("categoryId") String categoryId,
//            @RequestParam("description") String description,
//            @SessionAttribute("categoryId") String id,
//            @RequestParam("image") MultipartFile image, // 接收上传的文件
//            HttpServletResponse response) throws IOException {
//        log.info("添加新商品，商品ID：{}，商品名称：{}，分类ID：{}", productId, name, categoryId);
//        // 保存上传的图片到 images 文件夹
//        if (image != null && !image.isEmpty()) {
//
//            String imageName = name + ".gif"; // 图片文件名
//            String imagePath = "mypetstore-seller/src/main/resources/static/images/" + imageName; // 图片保存路径
//
//            // 将文件保存到指定路径
//            FileUtils.writeByteArrayToFile(new File(imagePath), image.getBytes());
//        }
//        categoryId=id;
//        Product product=new Product();
//        product.setProductId(productId);
//        product.setCategoryId(categoryId);
//        product.setName(name);
//        product.setDescription("<image src=\"../images/"+name+".gif\">"+description);
//        product.setDeleteFlag(0);//标记为有效
//        productService.insertProduct(product);
//        log.info("商品添加成功");
//        response.sendRedirect("/category2/view?catid="+categoryId);
//    }

}
